#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>

#define SIZE 1024

int main(void) {
	char prompt[] = "Type a command: ";
	char buf[SIZE];
	pid_t pid; // PID of child, pid_t is the same as int
	int status; // Exit status of child

	// Ask the user to type a command:
	// printf("%s", prompt);
	write(1, prompt, strlen(prompt));
	// Read from the standard input the command typed by the user 
	// (note that fgets also puts into the array buf the '\n' character typed
	// by the user when the user presses the Enter key on the keyboard
	// fgets(buf, SIZE, stdin);
	read(0, buf, SIZE);

	// Replace the Enter key typed by the user with '\0'
	for (int i = 0; i < SIZE; i++) {
		if (buf[i] == '\n' || buf[i] == '\r') {
			buf[i] = '\0';
			break;
		}
	}

	// Execute the command typed by the user (only prints it for now)
	// printf("Executing command: %s\n", buf);
	// write(1, buf, strlen(buf));
	// write(1, "\n", 1);
	pid = fork();  // New child process starts executing code from here
	if (pid < 0) { // No child process create
		printf("Parent: fork failed\n");
		return 1;
	} else if(pid == 0) {
		printf("Child: now running the program, doing exec\n");
		execlp(buf, buf, NULL);

		// if exec succeeded, the new child now starts executing the code of 
		// the main function of the xcalc program
		// The new child normally never executes the code below , unless exec failed.
		printf("Child: exec failed, die\n");
		return 1;  // child process dies after failed exec.
	} else {
		// code only executed by the parent process
		printf("Parent: Now sleeping and waiting for child %d to end\n", pid);
		wait(&status);
		printf("Parent: Finished waiting for child, child is dead\n");
		printf("Parent: Child exit status is %d\n", status);
		return 0; // parent process dies
	}
}

